import router from './index'
import store from '@/store/index'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

const whiteList = ['/login']

// 路由守卫
router.beforeEach(async (to, from, next) => {

    const hasToken = getToken()
    if (to.meta.isLogin) {
        if (hasToken) {
            if (to.path === '/login') {
                next({ path: '/'})
            } else {
                const hasGetUserInfo =store.getters.uid
                if (hasGetUserInfo) {
                    next()
                } else {
                    try {
                
                        await store.dispatch('user/getInfo')
                        next()
                    } catch (error) {
                        await store.dispatch('user/resetToken')
                        next()
                        Message.error(error || '出错了')
                        next(`/login?redirect=${to.path}`)
                    }
                }
                next()
            }
        } else {
            if (whiteList.indexOf(to.path) !== -1) {
                next()
            } else {
                next(`/login?redirect=${to.path}`)
            }
        }
    } else {
        next()
    }
    
})